package org.raymond.iworks.study.netty.atguigu.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        log.info("{}->: {}", ctx.channel().remoteAddress().toString(), buf.toString(CharsetUtil.UTF_8));

        // 自定义任务
        ctx.channel().eventLoop().execute(()->{
            try {
                Thread.sleep(5000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("等久了1".getBytes(CharsetUtil.UTF_8)));
            } catch (InterruptedException e) {
            }
        });

        ctx.channel().eventLoop().execute(()->{
            try {
                Thread.sleep(10000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("等久了2".getBytes(CharsetUtil.UTF_8)));
            } catch (InterruptedException e) {
            }
        });

        log.info("有个耗时的任务提交到任务队列里了");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端".getBytes(CharsetUtil.UTF_8)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("{}", cause.getMessage());
        ctx.close();
    }
}
